import e32, appuifw, positioning, httplib, urllib, urllib2
import location

def gps_init():
   #This function will start the updating of global variable (dictionary) 'gps_data' every 0.2 sec.
   #0.2 sec comes form 'interval = 200000' set according to your needs
   #This function uses callback funtion gps
   global gps_data
   #First this fills the gps_data with 0.0 so that there is something before the first gps update
   gps_data = {
   'satellites': {'horizontal_dop': 0.0, 'used_satellites': 0, 'vertical_dop': 0.0, 'time': 0.0,'satellites': 0, 'time_dop':0.0}, 
   'position': {'latitude': 0.0, 'altitude': 0.0, 'vertical_accuracy': 0.0, 'longitude': 0.0, 'horizontal_accuracy': 0.0}, 
   'course': {'speed': 0.0, 'heading': 0.0, 'heading_accuracy': 0.0, 'speed_accuracy': 0.0}
   }
   try:
      positioning.select_module(positioning.default_module())
      positioning.set_requestors([{"type":"service","format":"application","data":"gps_app"}])
      positioning.position(course=1,satellites=1,callback=gps, interval=200000,partial=0)
      e32.ao_sleep(3)
   except:
      appuifw.note(u'Problem with GPS','error')
 
def gps(event):
   global gps_data
   gps_data = event
 
def gps_stop():
   #This function stops GPS
   try:
      positioning.stop_position()
   except:
      appuifw.note(u'Problem with GPS','error')

def make_string(value):
    hex_s = hex(value)[2:]
    return hex_s.zfill(8)

def fetch_latlon(bytestring):
    url = 'http://www.google.com/glm/mmap'
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = { 'User-Agent' : user_agent }
    req = urllib2.Request(url, bytestring, headers)
    resp = urllib2.urlopen(req)
    response = resp.read().encode('hex')
    return response

def convert_bytestring(response):
    lathex_s = response[14:22]
    lonhex_s = response[22:30]
    lat = float(int(lathex_s,16))/1000000
    lon = float(int(lonhex_s,16))/1000000
    return (lat,lon)

def doLookup(cid,lac,mnc,mcc):    
    string1 = '000E00000000000000000000000000001B0000000000000000000000030000'
    string2 = 'FFFFFFFF00000000'
    string = string1+make_string(cid)+make_string(lac)+make_string(mnc)+make_string(mcc)+string2
    b_string = string.decode('hex')
    bytes = fetch_latlon(b_string)
    (a,b) = convert_bytestring(bytes)
    return a,b

def tweetme():
   try:
      gsm_latitude, gsm_longitude = doLookup(cellId, lac, mnc, mcc)
   except:
      print "doLookup error"   
   tweet=appuifw.query(u"Twit","text")
   pos_lat = gps_data['position']['latitude']
   pos_long = gps_data['position']['longitude']
   if(pos_lat==0):
      pos_lat=gsm_latitude
      pos_long=gsm_longitude
      appuifw.note(u'No GPS signal','info')
   if(tweet!=""):
      params = urllib.urlencode({'t': tweet.encode("utf-8"), 'lat': pos_lat, 'lon': pos_long, 'u': 'Cagnulein', 'p':'jocola5'})
      headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
      conn = httplib.HTTPConnection("www.cagnulein.com:80")
      conn.request("POST", "/googlemaps_localizer/index.php", params, headers)
      appuifw.note(u'Done','info')

def exit_key_handler():
   app_lock.signal()
 
gps_init()
appuifw.app.screen='normal'
app_lock=e32.Ao_lock()
round=appuifw.Text()
round.set(u'Action')
appuifw.app.body=round
appuifw.app.menu=[(u"Tweet",tweetme)]
appuifw.app.exit_key_handler=exit_key_handler
mcc=0
while mcc==0:
   try:   
      mcc, mnc, lac, cellId = location.gsm_location()  
   except:
      print "gsm error"
app_lock.wait()